<template>
  <div v-if="canShowPage" id="rolesList">
    <h1 class="con-right-title">
      角色管理
    </h1>
    <div class="bottom-box">
      <!--table-->
      <div class="table">
        <!--上部搜索条件-->
        <topSearch :form-inline="formInline" @toSearch="toSearch"></topSearch>
        <!-- 操作按钮 -->
        <div class="table-conBtn">
          <el-button
            v-if="powerAry.includes('system:role:add')"
            type="warning"
            icon="el-icon-plus"
            @click="addEditRoles('add')"
          >
            新增
          </el-button>
          <!-- <el-button type="warning" icon="el-icon-edit" @click="editRoles" :disabled="editdisabled">修改</el-button> -->
          <el-button
            v-if="powerAry.includes('system:role:remove')"
            type="warning"
            plain
            @click="delRoles"
          >
            批量删除
          </el-button>
          <el-button
            v-if="powerAry.includes('system:role:export')"
            type="warning"
            icon="el-icon-download"
            @click="exportRoles"
          >
            导出
          </el-button>
          <freshCom @searchList="LoadRole"></freshCom>
        </div>
        <!--下部table-->
        <el-table
          v-if="powerAry.includes('system:role:list')"
          v-loading="loading"
          :data="tableData"
          stripe
          style="width: 100%"
          @selection-change="handleSelectionChange"
          max-height="490"
          ref="table"
        >
          <el-table-column
            checked="true"
            type="selection"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column
            label="角色名称"
            prop="roleName"
            min-width="120"
          ></el-table-column>
          <el-table-column
            label="权限字符"
            prop="roleKey"
            min-width="120"
          ></el-table-column>
          <el-table-column
            label="显示顺序"
            prop="roleSort"
            min-width="120"
          ></el-table-column>
          <el-table-column label="角色状态" prop="status" min-width="120">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="0"
                :inactive-value="1"
                active-color="#1DC8A4"
                @change="
                  changeStatus(scope.row.status, scope.row.roleId, scope.$index)
                "
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            prop="createTime"
            min-width="160"
          ></el-table-column>
          <el-table-column
            label="创建人"
            prop="createBy"
            min-width="120"
          ></el-table-column>
          <el-table-column
            label="更新时间"
            prop="updateTime"
            min-width="160"
          ></el-table-column>
          <el-table-column
            label="更新人"
            prop="updateBy"
            min-width="120"
          ></el-table-column>
          <el-table-column fixed="right" label="操作" width="260">
            <template slot-scope="scope">
              <el-button
                v-if="powerAry.includes('system:role:edit')"
                type="text"
                @click="addEditRoles('edit', scope.row.roleId)"
              >
                编辑
              </el-button>
              <el-button type="text" @click="handledataAuth(scope.row.roleId)">
                数据权限
              </el-button>
              <el-button type="text" @click="handleSetUser(scope.row.roleId)">
                分配用户
              </el-button>
              <el-button
                v-if="powerAry.includes('system:role:remove')"
                type="text"
                @click="handledelRoles(scope.row.roleId)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-全局组件-->
        <pageCom
          :searchParams="searchParams"
          :total="total"
          @searchList="LoadRole"
        ></pageCom>
        <!-- 新增/编辑角色dialog -->
        <dialogAddEdit
          v-if="dialogData.isShow"
          :dialog-data="dialogData"
          @refresh="refresh"
        ></dialogAddEdit>
        <!-- 数据权限 -->
        <DataAuth
          v-if="authData.isShow"
          :auth-data="authData"
          @refresh="refresh"
          @dataAuth-success="LoadRole"
        ></DataAuth>
      </div>
    </div>
  </div>
</template>

<script>
import { getSearchList, disable, enable, deleteReq } from '@/api/system/roles' // 接口
import topSearch from '@component/system/roles/topSearch' // 上部搜索条件
import dialogAddEdit from '@component/system/roles/dialogAddEdit' // 新增/编辑
import DataAuth from '@component/system/roles/dataAuth' // 数据权限
import { saveScrollMixins } from '@/mixins/saveScroll'
export default {
  name: 'rolesList',
  msg: '角色管理-列表页',
  mixins: [saveScrollMixins],
  components: {
    topSearch,
    dialogAddEdit,
    DataAuth
  },
  data() {
    return {
      loading: true,
      total: 0,
      deptIds: [],
      roleSort: '', // 显示顺序
      tableData: [], // table内容
      searchParams: {
        pageNum: 1, // 当前页数
        pageSize: 10 // 页面显示条数
      },
      formInline: {
        // 搜索条件
        roleName: '', // 关键字
        roleKey: '', // 字符
        status: '', // 用户状态,默认所有
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        orderByColumn: '',
        isAsc: 'ASC',
        menuIds: [],
        createTime: []
      },
      editdisabled: true, // 修改按钮禁用状态
      deldisabled: true, // 批量删除按钮禁用状态
      dialogData: {
        isShow: false, // 默认隐藏
        type: 'add', // 默认新增
        roleId: null // 编辑时，传递的参数
      },
      authData: {
        isShow: false,
        params: null
      },
      multipleSelection: [], // 选中的行
      powerStr: 'system:role:list', // 是否查询的标识
      canGetList: true, // 是否可以查询列表
      powerAry: [], // 可显示的权限
      canShowPage: false // 是否显示当前页面
    }
  },
  computed: {
    userInfo() {
      return this.$store.state.user
    }
  },
  activated() {
    this.toTableScrollHeight()
  },
  mounted() {
    // 获取权限
    // this.getPower()
    this.$nextTick(() => {
      setTimeout(() => {
        this.setTableScrollHeight()
      }, 1000)
    })
  },
  methods: {
    /* 获取权限 */
    getPower() {
      let id = this.$route.query.mId
      this.getCurPageMenu(id).then((res) => {
        this.powerAry = res
        this.canShowPage = true
        if (!res.includes(this.powerStr)) {
          this.canGetList = false
          this.alertPower(this.powerStr)
        }
        this.LoadRole()
      })
    },
    /* 获取列表 */
    async LoadRole() {
      if (!this.canGetList) return
      this.loading = true
      let obj = Object.assign({}, this.searchParams, this.formInline)
      delete obj.createTime
      await getSearchList(
        obj,
        (response) => {
          this.loading = false
          this.tableData = response.rows
          this.total = response.total
        },
        (response) => {
          this.loading = false
          this.$message({
            message: response.message,
            type: 'warning'
          })
        }
      )
    },
    // 新增/编辑
    addEditRoles(type, params = '') {
      this.dialogData.isShow = true
      this.dialogData.type = type
      this.dialogData.roleId = params
    },
    // 导出
    exportRoles() {
      this.$confirm('确定导出所有用户吗？', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(
        () => {
          let url = '/roles/export'
          let params = Object.assign({}, this.searchParams, this.formInline)
          delete params.createTime
          delete params.startTime
          delete params.endTime
          this.downFile('get', url, params, '角色管理')
        },
        (response) => {
          this.loading = false
        }
      )
    },
    // 数据权限
    handledataAuth(roleId) {
      this.authData.isShow = true
      this.authData.params = roleId
    },
    // 跳转分配用户页面
    handleSetUser(id) {
      let query = {
        mId: this.$route.query.mId
      }
      this.$router.push({ name: 'setUser', params: { id }, query: query })
    },
    // 批量删除
    delRoles() {
      if (this.multipleSelection.length <= 0) {
        this.$message.warning('请至少选择一条数据！')
        return
      }
      this.$confirm(
        `确认删除选中的这${this.multipleSelection.length}条数据吗？`,
        '删除提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          let roleIds = []
          this.multipleSelection.forEach((item) => {
            roleIds.push(item.roleId)
          })
          this.delItem(roleIds)
        })
        .catch(() => {
          this.LoadRole()
        })
    },
    // 删除单个
    handledelRoles(roleId) {
      this.$confirm('确认删除该条信息吗？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.delItem([roleId])
        })
        .catch(() => {
          this.LoadRole()
        })
    },
    /* 删除请求 */
    async delItem(roleIds) {
      let obj = { roleIds: roleIds.join(',') }
      // let params = this.changeToForm(obj)
      await deleteReq(
        obj,
        (response) => {
          this.LoadRole()
        },
        (response) => {
          this.$message({
            message: response.message,
            type: 'warning'
          })
        }
      )
    },
    // checkbox选中事件
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 状态切换提示
    async changeStatus(status, id, index) {
      let _this = this
      // 只有关闭才会弹框
      if (status === 1) {
        // 关闭
        this.$confirm('确认要停用该角色吗？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            disable(id, (response) => {
              this.$message({
                type: 'success',
                message: '已停用'
              })
            })
          })
          .catch(() => {
            this.tableData[index].status = '0'
            /* this.$message({
                 type: "info",
                 message: "已取消停用"
               }); */
          })
      } else {
        // 启用
        await enable(id, (response) => {
          this.$message({
            type: 'success',
            message: '已启用'
          })
        })
      }
    },
    /* 新增编辑后，刷新列表 */
    refresh() {
      this.toSearch()
    },
    /* 换页 */
    changePage(page) {
      this.searchParams.pageNum = page
      this.LoadRole()
    },
    /* 搜索 */
    toSearch() {
      this.searchParams.pageNum = 1
      this.LoadRole()
    }
  }
}
</script>

<style lang="less">
#rolesList {
  height: 100%;

  .search-box {
    padding-left: 30px !important;
  }

  .bottom-box {
    position: relative;
    height: calc(~'100% - 40px');
    .table-conBtn {
      padding-left: 30px !important;
    }

    .left-tree {
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      /*  background: #8cc5ff;*/
      width: 192px;
      height: calc(~'100% - 20px');
      overflow: hidden;

      &.hide-tree {
        width: 12px;
      }

      span.btn-arrow {
        position: absolute;
        top: 50%;
        right: 0;
        margin-top: -25px;
        width: 12px;
        height: 50px;
        text-align: center;
        line-height: 50px;
        background: #ddd;
        cursor: pointer;

        &:hover {
          background: #ff8c00;
        }
      }
    }

    .table {
      &.hide-tree {
        margin-left: calc(~'12px + 20px');
      }
    }
  }
}
</style>
